/*
 * Copyright (C) 2008  Wang Hoi <fearee@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  US
*/
#ifndef BUFFER_H
#define BUFFER_H
#include <QtCore>
#include "ts.h"
#include "memcache.h"
#include "filecache.h"
#include "source.h"
class Server;
class Connection;
class Buffer: public QObject
{
    Q_OBJECT
public:
    Buffer(const QString &, AbstractSource *, Server *);
    ~Buffer();
    void getData(quint64);
    qint64 timeToPos(qint64);
Q_SIGNALS:
    void dataReady(quint64, const QByteArray &);
    void underBuffer(quint64);
private Q_SLOTS:
    void onSourceGotData(const QByteArray &);
    void onSourceReset();
    void onMemCacheGot(const QString &, const QByteArray &);
    void onMemCacheSet(const QString &, const QByteArray &);
    void onMemCacheDel(const QString &);
    void onMemCacheErr(const QString &);
    void onFileCacheGot(const QString &, const QByteArray &);
    void onFileCacheSet(const QString &, const QByteArray &);
    void onFileCacheDel(const QString &);
    void onFileCacheErr(const QString &);
    void onMemBufferTimeOut();
    void onFileBufferTimeOut();
private:
    void store(const QString &, const QByteArray &);
    void parseTS(const QByteArray &);

    QString id;

    quint64 currentPos;
    quint64 earliestTime;
    quint64 latestTime;
    ts_t *ts;

    quint64 chunkSize;

    quint64 maxMemTime;
    quint64 maxFileTime;
    quint64 memOldest;
    quint64 fileOldest;

    QList<QTimer *> memTimers;
    QList<QTimer *> fileTimers;

    QMap<quint64, quint64> timeMap;
    QQueue<QString> memBuffers;
    QQueue<QString> fileBuffers;
    QByteArray mbuffer;
    QByteArray parseBuffer;

    Server *srv;
    AbstractSource *src;
    MemCache *memCache;
    FileCache *fileCache;

};
#endif
